public without sharing class CreditchangeController {

	public String dataJson {get; set;}
    public String msg {get;private set;}
    public Boolean isErr {get; private set;}//错误
    public Boolean isSuccess {get; private set;}//是否保存成功
    public String backId {get; private set;}
    public String saveJson {get;set;}

    public String newAccRate {get;private set;}//客户信用评级

    private  Map<String,DataUtil.SObjectBean> stageObjectMap;
    private Creditchange__c cc ;
    public CreditchangeController() {
         stageObjectMap = new Map<String,DataUtil.SObjectBean> ();
         cc = new Creditchange__c();
         backId = System.currentPageReference().getParameters().get('id');

    }

    public void init(){
    	//AccountCredit__c

    		try {

    		  	 if(String.isBlank(backId)) throw new DmlException('打开错误!');

    		  	 Account acc = new Account();
    		  	 SObjectType st = Id.valueOf(backId).getSObjectType();
    		  	 String retype= null;
    		  	 if(st == Creditchange__c.SObjectType ){
    		  	 	//编辑
    		  	 	cc = [select Id ,stage__c ,Account__c,Account__r.Name,FormerApprovedCreditline__c,CreditDeadlineOld__c ,Account__r.RecordType.DeveloperName ,AccountCredit__c,Company__c , AccountCredit__r.Name from Creditchange__c where Id =:backId];
    		  	 	if(cc.stage__c == '审批通过' || cc.stage__c == '审批中	' )throw new DmlException(cc.stage__c +',不能修改!');

    		  	 	acc.Id = cc.Account__c;
    		  	 	acc.Name =cc.Account__r.Name ;
    		  	 	retype = cc.Account__r.RecordType.DeveloperName; 
    		  	 }else if(st == Account.SObjectType){

    		  	 	User u = [select Id,SubCompany__c from User where Id=:UserInfo.getUserId()];
    		  	 	//新建 
    		  	 	List<AccountCredit__c> acL = [select Id,Name,Account__c,Account__r.Name,Account__r.RecordType.DeveloperName  ,NCCreditDeadline__c,CreditLimit__c ,Company__c from AccountCredit__c where Account__c =:backId and Company__c =:u.SubCompany__c ];

    		  	 
    		  	 	if(acL.isEmpty())throw new DmlException('没有客户信用!请先做NC客户准入申请!'); 

    		  	 	acc.Id = acl.get(0).Account__c;
    		  	 	acc.Name = acl.get(0).Account__r.Name ;
					retype = acl.get(0).Account__r.RecordType.DeveloperName;
    		  	 	cc.AccountCredit__c = acl.get(0).Id;
    		  	 	cc.Account__c = acl.get(0).Account__c;
    		  	 	cc.Company__c = u.SubCompany__c;

    		  	 	cc.FormerApprovedCreditline__c = acl.get(0).CreditLimit__c;
    		  	 	cc.CreditDeadlineOld__c = acl.get(0).NCCreditDeadline__c;

    		  	 }

    		  


    		  	 Id rId = Utils.getRecordTypeIdByDevNameAndObjName(retype, 'CustomerCreditRatings__c');
	    			
	    		//newAccRate ='/'+crId.substring(0,3)+'/e?CF00N2800000JH2xe='+acc.Name  +'&CF00N2800000JH2xe_lkid='+acc.Id+'&retURL=%2F'+acc.Id+'&RecordType='+ rId;
    		  	 setNewAccRate(rId,acc);
	    	 	//字段
	             Map<String,Set<String>> fieldsmap = getFields();
	             //字段详情
	             Map<String, List<DataUtil.FieldBean>> fbMap = DataUtil.getFieldsBean(fieldsmap,stageObjectMap);
	            
	            //字段赋值
	             Map<String,List<DataUtil.FieldBean>> fields = DataUtil.setFieldsValue(fbMap,DataUtil.getBaseInfo(fbMap,stageObjectMap) );
	             Map<String,Object> dataMap = new Map<String,Object>();
	            dataMap.put('base',fields);
	            dataMap.put('baseObject',DataUtil.getBaseObjectMap(stageObjectMap)); 
	            for (DataUtil.FieldBean fb   :  fields.get('Creditchange__c')) {
	                Map<String,Object> vMap  = new Map<String,Object>();
	                if(fb.name == 'Account__c'){

	                    vMap.put('Id', acc.Id );
	                    vMap.put('Name', acc.Name );
	                    fb.value = vMap;
	                }
	                if(fb.name == 'FormerApprovedCreditline__c')fb.value = cc.FormerApprovedCreditline__c;
	                if(fb.name == 'CreditDeadlineOld__c')fb.value = cc.CreditDeadlineOld__c;
	                if(fb.name == 'Company__c')fb.value = cc.Company__c;


	             }
	            dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap), 'UTF-8');

    		}catch (Exception e) {
    		     isErr = true;
                ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
    		}


    }

    private void  setNewAccRate(String rid  , Account acc ){

    	newAccRate =  Label.CustomerCreditRatings;
    	newAccRate = newAccRate.replaceAll('accName', acc.Name);
    	newAccRate = newAccRate.replaceAll('accId', acc.Id );
    	newAccRate = newAccRate.replaceAll('rId', rid);

    }

    public Map<String,Set<String>>  getFields(){
        Map<String,Set<String>> fieldsMap  = new  Map<String,Set<String>>();
        
            DataUtil.SObjectBean sb = new DataUtil.SObjectBean();

            sb.title ='信用变更申请';
            sb.objname = 'Creditchange__c';
            sb.stype = DataUtil.getSObjectType(sb.objname);
            sb.type = 'base';
            sb.idvalue = cc.Id;
            sb.condition = ' where Id =\''+cc.Id+'\'';
            stageObjectMap.put(sb.objname,sb );
            //安装类型 安装仪器 Supplier__c
            Set<String>  fields = new Set<String>{'Account__c','ExcuteStartDate__c','ApprovalDebtAmount__c',

           'Remark__c','MonthlySalesAmount__c','Company__c','ApprovalDelayDays__c','AssociatedCreditRating__c',

           'CreditPeriod__c','CreditLimit__c' ,'FormerApprovedCreditline__c','CreditDeadlineOld__c'};
            //,'CreditLimit__c','FormerApprovedCreditline__c',

         fieldsMap.put(sb.objname, fields);
            

        
        return fieldsMap;
    }


    public void save(){

        msg = '';
        Map<String,Object>saveMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
        Map<String,Set<String>> fieldsMap = getFields();
        Map<String,DataUtil.FieldBean> fbeanMap = DataUtil.getFieldsInfo(Creditchange__c.SObjecttype,fieldsMap.get('Creditchange__c'));

            for (String field :  saveMap.keySet()) {

                if(saveMap.get(field) == null || DataUtil.getStringValue(saveMap.get(field)) == '') continue;

               cc.put(field, DataUtil.dataHandler(saveMap.get(field),fbeanMap.get(field).type.toUpperCase() ));

            }
            
        
        SavePoint sp = Database.setSavepoint();

        try {

           
            upsert cc;
            backId = cc.Id;
            isSuccess = true;
            msg = '保存成功!';

        }catch (Exception e) {
            Database.rollback(sp);
            msg = '保存失败:'+e.getMessage()+e.getStackTraceString();

        }
        

    }
}